package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.HuaWei.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.IotMsgService;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备管理Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-23
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) {
        //1.判断设备名称是否重复
        Long count = this.lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if(count>0){
            throw new BaseException("设备名称重复");
        }
        //2.判断设备标识是否重复
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        //3.判断同一位置是否绑定了相同的产品
        //select count（*）from device
        // where binding_location=? and Location_type=? and product_key=?
        Long countLocation = this.lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                //.eq(Device::getDeviceName, deviceDto.getDeviceName())
                .eq(Device::getProductKey,deviceDto.getProductKey())
                .count();
        if(countLocation>0){
            throw new BaseException("不能绑定同样的设备");
        }
        //4.册设备到华为云IOT平台
        AddDeviceRequest adr = new AddDeviceRequest();
        AddDevice ad = new AddDevice();
        ad.setNodeId(nodeId);
        ad.setDeviceName(deviceDto.getDeviceName());//英文名
        ad.setDescription(deviceDto.getNickname());//中文名
        ad.setProductId(deviceDto.getProductKey());//产品key
        //设备密钥
        String secret = IdUtil.fastSimpleUUID();
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        ad.setAuthInfo(authInfo);
        adr.setBody(ad);
        try {
            AddDeviceResponse response = client.addDevice(adr);
            if (response.getHttpStatusCode()!=HttpStatus.HTTP_CREATED){
                throw new BaseException("注册到IOT平台失败");
            }
            String iotId = response.getDeviceId();//平台生成
            //5. 设备表新增数据
            Device device = BeanUtil.toBean(deviceDto, Device.class);
            device.setIotId(iotId); //设备唯一ID
            device.setNodeId(nodeId); //设备唯一标识
            device.setSecret(secret); //设备密钥
            device.setHaveEntranceGuard(deviceDto.getNickname().contains("门禁") ? 1: 0 );//是否门禁

            String productId = deviceDto.getProductKey();
            String productName = getProductNameFromCache(productId);
            if(StrUtil.isNotBlank(productName)) {
                device.setProductName(productName);//产品名称
            }
            this.save(device);
        } catch (BaseException e) {
            e.printStackTrace();
            throw new BaseException("注册到IOT平台失败");
        }


    }
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;
    /**
     * 获取设备详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId,String productKey) {
        //1. 查询表中设备
        Device device = this.lambdaQuery()
                //iotId 是设备在物联网平台的唯一标识
                //productKey 是设备所属产品类型的标识
                //两者组合可以唯一确定一个设备实体
                .eq(Device::getIotId, iotId)
                .eq(Device::getProductKey, productKey)
                //获取单个对象
                .one();
        if(device == null){
            throw new BaseException("表中设备不存在");
        }
        //2.查询华为云IOTDA平台中设备详情
        //ShowDeviceRequest：这是华为云 IoTDA SDK 提供的请求类，用于查询设备详细信息
        //withDeviceId()：设置要查询的设备 ID（iotId），这是设备在华为云平台上的唯一标识
        //client.showDevice()：调用 IoTDA 客户端的 showDevice 方法，传入请求对象，获取设备详细信息
        ShowDeviceRequest sdr = new ShowDeviceRequest();
        sdr.withDeviceId(iotId);//设备唯一ID
        ShowDeviceResponse response = client.showDevice(sdr);
        if(response.getHttpStatusCode()!=HttpStatus.HTTP_OK){
            throw new BaseException("IOT平台中设备不存在");
        }
        //3.合并数据
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setGmtCreate(device.getCreateTime());//创建时间
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());//地域
        vo.setDeviceSecret(device.getSecret());//设备id
        Long sysUserId = Long.valueOf(device.getCreateBy());
        SysUser sysUser = iSysUserService.selectUserById(sysUserId);
        vo.setCreator(sysUser.getUserName());//创建人名称
        vo.setDeviceStatus(response.getStatus());//设备状态
        vo.setFirmwareVersion(response.getFwVersion());//固件版本
        String activeTime = response.getActiveTime();
        if(StrUtil.isNotBlank(activeTime)){
            LocalDateTime gmtActice = OffsetDateTime.parse(activeTime)
                    //将 OffsetDateTime 转换为 ZonedDateTime
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setGmtActive(gmtActice);//激活时间
        }
        return vo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param dto
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(DeviceDto dto) {
        //1．调用IOT平台的接口查询产品,获取请求参数
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.withProductId(dto.getProductKey());
        ShowProductResponse showProductResponse = client.showProduct(showProductRequest);
        if(showProductResponse.getHttpStatusCode()!=HttpStatus.HTTP_OK){
            throw new BaseException("产品在IoT平台不存在");
        }
        //2．解析响应结果
        //ServiceCapability 包含的信息：
        //serviceId - 服务ID
        //serviceType - 服务类型
        //properties - 属性列表
        //commands - 命令列表
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        if(CollUtil.isNotEmpty(serviceCapabilities)){
            ServiceCapability serviceCapability = serviceCapabilities.get(0);
            JSONObject jsonObject = JSONUtil.parseObj(serviceCapability);
            return jsonObject;
        }
        return null;
    }



    /**
     * 查询指定设备的物模型运行状态(设备上报的数据)
     *
     * @param productKey
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String productKey, String deviceName) {
        //从表中查询设备信息
        Device device = this.lambdaQuery().eq(Device::getProductKey, productKey)
                .eq(Device::getDeviceName, deviceName)
                .one();
        if(device==null) {
            throw new BaseException("表中设备不存在");
        }

        //调用IOT云平台接口查询设备影子信息
        ShowDeviceShadowRequest showDeviceShadowRequest = new ShowDeviceShadowRequest();
        showDeviceShadowRequest.withDeviceId(device.getIotId());//设备ID
        ShowDeviceShadowResponse response = client.showDeviceShadow(showDeviceShadowRequest);
        if(response.getHttpStatusCode()!=HttpStatus.HTTP_OK) {
            throw new BaseException("没有上报数据");
        }

        //解析响应结果
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if(CollUtil.isEmpty(shadowDataList)) {
            return Collections.emptyMap();
        }
        String eventTime = shadowDataList.get(0).getReported().getEventTime();//物模型属性数据上报时间，格式：20151212T121212Z
        if(StrUtil.isNotBlank(eventTime)) {
            LocalDateTime reportTime = OffsetDateTime.parse(eventTime,DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //上报的属性对象数据集合
            List<Map<String,Object>> propertyStatusInfoList = new ArrayList<>();
            JSONObject propertiesJSONObject = JSONUtil.parseObj(shadowDataList.get(0).getReported().getProperties());
            propertiesJSONObject.forEach((k,v)->{
                String propertyName = k; //上报的属性名
                Object propertyValue = v; //上报的属性值

                Map<String,Object> propertyMap = new HashMap<>();
                propertyMap.put("identifier",propertyName);
                propertyMap.put("value", propertyValue);
                propertyMap.put("time",reportTime);
                propertyStatusInfoList.add(propertyMap);
            });

            Map<String,Object> propertyStatusInfoMap = new HashMap<>();
            propertyStatusInfoMap.put("propertyStatusInfo",propertyStatusInfoList);

            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("list",propertyStatusInfoMap);

            return resultMap;
        }
        return null;
    }
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 基于IOT设备上传通知的数据，批量保存设备数据
     *
     * @param notifyData
     */
    @Override
    public void saveBatchData(IotMsgNotifyData notifyData) {
        //1．判断设备是否存在
        String deviceId = notifyData.getHeader().getDeviceId();
        Device device = this.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        //2.获取上报的服务信息
        List<IotMsgService> serviceList = notifyData.getBody().getServices();
        serviceList.forEach(x -> {
            //3.取上报的物模型数据信息
            Map<String, Object> properties = x.getProperties();
            String eventTime = x.getEventTime();
            LocalDateTime alertTime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            /*properties.forEach((k,v)->{
                //
                String functionId = k;//功能名（设备的物模型属性名）
                Object dataValue = v;//属性上报的值
                DeviceData.builder()
                        .deviceName(device.getDeviceName())//设备名
                        .iotId(deviceId)//设备id
                        .nodeId(device.getNodeId())//节点id
                        .nickname(device.getNickname())//设备昵称
                        .productKey(device.getProductKey())//产品key
                        .productName(device.getProductName())//产品名
                        .functionId(functionId)
                        .dataValue(String.valueOf(dataValue))
                        .accessLocation(device.getBindingLocation())//绑定位置
                        .locationType(device.getLocationType())//位置类型
                        .physicalLocationType(device.getPhysicalLocationType())//物理位置
                        .alarmTime(alertTime)//数据上报时间
                        .build();
            });*/
            List<DeviceData> deviceDataList = properties.entrySet().stream().map(entry -> {
                String functionId = entry.getKey();
                Object dataValue = entry.getValue();
                DeviceData deviceData = DeviceData.builder()
                        .deviceName(device.getDeviceName())//设备名
                        .iotId(deviceId)//设备id
                        .nodeId(device.getNodeId())//节点id
                        .nickname(device.getNickname())//设备昵称
                        .productKey(device.getProductKey())//产品key
                        .productName(device.getProductName())//产品名
                        .functionId(functionId)
                        .dataValue(String.valueOf(dataValue))
                        .accessLocation(device.getBindingLocation())//绑定位置
                        .locationType(device.getLocationType())//位置类型
                        .physicalLocationType(device.getPhysicalLocationType())//物理位置
                        .alarmTime(alertTime)//数据上报时间
                        .deviceDescription(device.getDeviceDescription())//设备描述
                        .build();
                return deviceData;
            }).collect(Collectors.toList());
        // 4.批量插入数据
        deviceDataService.saveBatch(deviceDataList);
        log.info("设备信息: {}", device);
            //5. 存入到redis  key：hash数据类型（大key，小key,  value）iot:device_last_data   iot_id
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId(), JSONUtil.toJsonStr(deviceDataList));
        });
    }
        @Autowired
        private IDeviceDataService deviceDataService;

    /**
     * 从缓存中获取产品名称
     * @param productId
     * @return
     */
    private String getProductNameFromCache(String productId) {
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if(StrUtil.isBlank(jsonStr)) {
            return null;
        }

        List<ProductSummary> productSummaryList = JSONUtil.toList(jsonStr, ProductSummary.class);
        ProductSummary productSummary = productSummaryList.stream().filter(x -> productId.equals(x.getProductId())).findFirst().get();
        if(productSummary!=null) {
            return productSummary.getName();//产品名
        }
        return null;
    }

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }



    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 根据物联网平台ID删除设备
     *
     * @param iotId 物联网平台设备ID
     * @param productKey 产品Key
     * @return 结果
     */
    public boolean deleteDeviceByIotId(String iotId, String productKey) {
        // 1. 先从华为云IoTDA平台删除设备
        DeleteDeviceRequest deleteRequest = new DeleteDeviceRequest();
        deleteRequest.setDeviceId(iotId);
        try {
            DeleteDeviceResponse response = client.deleteDevice(deleteRequest);
            if (response.getHttpStatusCode() != HttpStatus.HTTP_OK) {
                log.error("从华为云平台删除设备失败, HTTP状态码: {}", response.getHttpStatusCode());
                return false;
            }
        } catch (Exception e) {
            log.error("调用华为云删除设备接口异常", e);
            return false;
        }

        // 2. 从本地数据库删除设备记录
        Long count = this.lambdaQuery()
                .eq(Device::getIotId, iotId)
                .eq(Device::getProductKey, productKey)
                .count();

        if (count > 0) {
            boolean result = this.lambdaUpdate()
                    .eq(Device::getIotId, iotId)
                    .eq(Device::getProductKey, productKey)
                    .remove();
            return result;
        }
        return true;
    }


    @Autowired
    private IoTDAClient client;
    /**
     * 物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        try {
            //1.用IOT平台接口查询产品列表
            ListProductsResponse response = client.listProducts(new ListProductsRequest());
            if(response.getHttpStatusCode()!= HttpStatus.HTTP_OK){
                throw new BaseException("同步产品列表失败");
            }
            //2.取响应结果的产品列表
            List<ProductSummary> products = response.getProducts();
            if(CollUtil.isNotEmpty(products)){
                //3.产品列表转为JSON字符串
                String jsonStr = JSONUtil.toJsonStr(products);
                //4.JSON字符串存入Redis
                redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY,jsonStr);
            }
        } catch (BaseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从Redis查询产品列表JSON字符串
        String productListJson = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if(StringUtils.isBlank(productListJson)) {
            //返回一个空集合
            return Collections.emptyList();
        }
        //解析JSON为产品列表
        List<ProductSummary> productList = JSONUtil.toList(productListJson, ProductSummary.class);
        //遍历产品列表，转为前端需要的数据类型
        List<ProductVo> productVoList = productList.stream().map(x -> {
            return ProductVo.builder()
                    .productKey(x.getProductId())
                    .productName(x.getName())
                    .build();
        }).collect(Collectors.toList());
        return productVoList;
    }
    /**
     * 修改设备备注名称
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceInfo(DeviceDto dto) {
        String iotId = this.getById(dto.getId()).getIotId();
        Device device = BeanUtil.toBean(dto, Device.class);
        // 修改数据表中设备数据
        this.updateById(device);
        // 修改IOT信息
        UpdateDeviceRequest updateDeviceRequest = new UpdateDeviceRequest();
        updateDeviceRequest.withDeviceId(iotId);
        UpdateDevice updateDevice = new UpdateDevice();
        updateDevice.setDescription(dto.getNickname());
        updateDevice.setDeviceName(dto.getDeviceName());
        updateDeviceRequest.withBody(updateDevice);
        try {
            UpdateDeviceResponse response = client.updateDevice(updateDeviceRequest);
            if (response.getHttpStatusCode() != HttpStatus.HTTP_OK) {
                throw new BaseException("调用接口失败");
            }


        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("调用接口失败");
        }
    }
    /**
     * 删除设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteInfo(DeviceDto dto) {
        // 删除数据库中的信息
        this.remove(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, dto.getIotId())
                .eq(Device::getProductKey, dto.getProductKey()));

        // 删除IOT平台的信息
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setDeviceId(dto.getIotId());
        try {
            DeleteDeviceResponse response = client.deleteDevice(deleteDeviceRequest);
            // 404表示设备不存在，可以忽略
            if (response.getHttpStatusCode() != HttpStatus.HTTP_NO_CONTENT &&
                    response.getHttpStatusCode() != HttpStatus.HTTP_NOT_FOUND) {
                throw new BaseException("调用接口失败");
            }
        } catch (Exception e) {
            // 如果是404错误，忽略
            if (!(e instanceof ServiceResponseException &&
                    ((ServiceResponseException)e).getHttpStatusCode() == 404)) {
                e.printStackTrace();
                throw new BaseException("调用接口失败");
            }
        }
    }

}
